package com.hankol.newretail.fragment

import androidx.lifecycle.Observer
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseFragment
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.toast
import com.baselibrary.utils.EventBusUtils
import com.baselibrary.utils.TimeUtil
import com.hankol.newretail.R
import com.hankol.newretail.adapter.SeckillAdapter
import com.hankol.newretail.adapter.details.GoodsDetailAdapter
import com.hankol.newretail.databinding.FragmentSeckillBinding
import com.hankol.newretail.viewmodel.SeckillViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 秒杀Viewpager的Fragment
 */
class SeckillFragment(private var showType: String, private var cid: Int) : BaseFragment() {
    private lateinit var mBinding: FragmentSeckillBinding
    private lateinit var mAdapter: SeckillAdapter
    private lateinit var viewModel: SeckillViewModel
    var page = 1
    private var hasnext: Boolean = false
    var currentClickSeckillPosition = 0

    //防止横屏崩溃
    constructor() : this("", 0)

    companion object {
        //showType:2 酒窖全部秒杀
        fun newInstance(showType: String, cid: Int): SeckillFragment {
            return SeckillFragment(showType, cid)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_seckill
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        mBinding = getDataBinding()
        viewModel = getFragmentViewModelProvider(this).get(SeckillViewModel::class.java)
        if (showType == "0") {
            mAdapter = SeckillAdapter(R.layout.item_seckill_single, arrayListOf())
        } else {
            mAdapter = SeckillAdapter(R.layout.item_seckill, arrayListOf())
        }
        mAdapter.setShowType(showType)

        mAdapter.setClickButtonListener(object : GoodsDetailAdapter.ClickButtonListener {
            override fun onClickButton(status: Int, position: Int, actId: Int) {
                currentClickSeckillPosition = position
                when (status) {
                    1 -> viewModel.reqSeckillCancelSubscribe(actId.toString())
                    2 -> viewModel.reqSeckillAddSubscribe(actId.toString())
                }
            }
        })
        mBinding.rvSeckill.adapter = mAdapter
        initListener()
        addObserver()
        loadData()
    }

    private fun initListener() {
        mBinding.smartRefresh.setEnableRefresh(showType == "2")
        mBinding.smartRefresh.setOnRefreshListener {
            page = 1
            loadData()
        }
        mBinding.smartRefresh.setOnLoadMoreListener {
            if (hasnext) {
                loadData()
            } else {
                mBinding.smartRefresh.finishLoadMore()
            }
        }
    }

    private fun loadData() {
        if (showType == "0" || showType == "1") {
            viewModel.reqSeckillCategoryActList(cid, page)
        } else if (showType == "2") {
            viewModel.reqSeckillWineryActList(cid, page)
        }
    }

    private fun addObserver() {
        viewModel.seckillCategoryActListLD.observe(this, Observer {
            mBinding.smartRefresh.finishRefresh()
            EventBusUtils.sendNotify(MessageBus.msgId_refresh_seckill_complete)
            if (it.data.isNotEmpty()) {
                if (it.data.checkNotNull()) {
                    hasnext = it.hasnext
                    mBinding.smartRefresh.finishLoadMore()
                    if (page == 1) {
                        mAdapter.setNewData(it.data)
                    } else {
                        mAdapter.addData(it.data)
                    }
                    page++
                    mBinding.smartRefresh.setEnableLoadMore(it.totalCount!=mAdapter.data.size)
                } else {
                    mBinding.smartRefresh.finishLoadMore()
                }
            }
        })

        //秒杀--取消预约
        viewModel.seckillCancelSubLD.observe(this, Observer {
            //取消预约成功
            mAdapter.data[currentClickSeckillPosition].seckillActProductExtDTO?.subscribeFlg = 0
            mAdapter.data[currentClickSeckillPosition].seckillActProductExtDTO?.subscribeNum = mAdapter.data[currentClickSeckillPosition].seckillActProductExtDTO?.subscribeNum?.minus(1)!!
            mAdapter.notifyItemChanged(currentClickSeckillPosition)
            "取消预约成功".toast()
        })
        //秒杀--添加预约
        viewModel.seckillAddSubLD.observe(this, Observer {
            com.baselibrary.utils.PopUtils.showSeckillInternetSuccessDialog(attachActivity, TimeUtil.setYearMonthDay(it.stime), "${it.subscribeRemind}")
            mAdapter.data[currentClickSeckillPosition].seckillActProductExtDTO?.subscribeFlg = 1
            mAdapter.data[currentClickSeckillPosition].seckillActProductExtDTO?.subscribeNum = mAdapter.data[currentClickSeckillPosition].seckillActProductExtDTO?.subscribeNum?.plus(1)!!
            mAdapter.notifyItemChanged(currentClickSeckillPosition)
        })
    }
    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN) fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_refresh_seckill){
            page = 1
            loadData()
        }
    }
    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }

}